<template>
  <div class='app-container'>
    <el-card :body-style="{ padding: '20px' }">
      <div slot="header">
        <span>{{title}}</span>
      </div>
      <el-form
        ref="addFormData"
        label-width="120px"
        :model="formData"
        :rules='formDataRules'
      >
        <el-form-item
          label="学科："
          prop="subjectID"
        >
          <el-select
            placeholder="请选择"
            v-model="formData.subjectID"
            @focus="getSubjectData"
          >
            <el-option
              v-for="item in subject"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="目录："
          prop="catalogID"
        >
          <el-select
            placeholder="请选择"
            v-model="formData.catalogID"
            @focus="getCatalogData"
          >
            <el-option
              v-for="item in catalog"
              :key="item.id"
              :label="item.directoryName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="企业："
          prop="enterpriseID"
        >
          <el-select
            placeholder="请选择"
            v-model="formData.enterpriseID"
            @focus="getEnterpriseData"
          >
            <el-option
              v-for="item in enterprise"
              :key="item.id"
              :label="item.company"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="城市："
          prop="province"
        >
          <el-row style="width:400px">
            <el-select
              placeholder="请选择"
              style="width:198px"
              v-model="formData.province"
            >
              <el-option
                v-for="item in provinces"
                :key="item"
                :label="item"
                :value="item"
              ></el-option>

            </el-select>
            <el-select
              v-model="formData.city"
              placeholder="请选择"
              style="width:198px; margin-left:4px;"
              @focus="getCitysData"
            >
              <el-option
                v-for="item in citys"
                :key="item"
                :value="item"
              ></el-option>

            </el-select>
          </el-row>
        </el-form-item>
        <el-form-item
          label="方向："
          prop="direction"
        >
          <el-select
            placeholder="请选择"
            v-model="formData.direction"
          >
            <el-option
              v-for="item in direction"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>

          </el-select>
        </el-form-item>
        <el-form-item
          label="题型："
          prop="questionType"
        >
          <el-radio
            v-for="item in questionType"
            :key="item.value"
            :label="item.value + ''"
            v-model="formData.questionType"
          >{{item.label}}</el-radio>
        </el-form-item>
        <el-form-item
          label="难度："
          prop="difficulty"
        >
          <el-radio
            v-for="item in difficulty"
            :key="item.value"
            :label="item.value + ''"
            v-model="formData.difficulty"
          >{{item.label}}</el-radio>
        </el-form-item>
        <el-form-item
          label="题干："
          prop="question"
        >
          <!-- 后期添加富文本组件 -->
          <quill-editor v-model="formData.question" />
        </el-form-item>
        <!-- 单选显示 -->
        <el-form-item
          v-if="formData.questionType === '1'"
          label="选项："
          prop="options"
        >
          <el-row
            class="option_item"
            v-for="item in options"
            :key="item.code"
          >
            <el-radio
              :label="item.code"
              style="margin-right:0"
              v-model="isRadio"
            >{{item.code + '：'}}</el-radio>
            <el-input
              style="width:240px"
              v-model="item.title"
            />
            <el-upload
              class="avatar-uploader"
              action="#"
              list-type="picture-card"
            >
              <span>上传图片</span>
              <i class="el-icon-circle-close"></i>
            </el-upload>
          </el-row>
          <el-row class="option_item">
            <el-button
              type="danger"
              size="small"
              disabled
            >+增加选项与答案</el-button>
          </el-row>
        </el-form-item>
        <!-- 多选显示 -->
        <el-form-item
          label="选项："
          prop="options"
          v-else-if="formData.questionType === '2'"
        >
          <el-row
            class="option_item"
            v-for="item in options"
            :key="item.code"
          >
            <el-checkbox
              :label="item.code"
              style="margin-right:0"
              v-model="isCheckbox"
            >{{item.code + '：'}}</el-checkbox>
            <el-input
              style="width:240px"
              v-model="item.title"
            />
            <el-upload
              class="avatar-uploader"
              action="#"
              list-type="picture-card"
            >
              <span>上传图片</span>
              <i class="el-icon-circle-close"></i>
            </el-upload>
          </el-row>
          <el-row class="option_item">
            <el-button
              type="danger"
              size="small"
              @click="btnAdd"
            >+增加选项与答案</el-button>
          </el-row>
        </el-form-item>
        <el-form-item
          label="解析视频："
          prop="videoURL"
        >
          <el-input
            style="width:400px"
            v-model="formData.videoURL"
          />
        </el-form-item>
        <el-form-item
          label="答案解析："
          prop="answer"
        >
          <!-- 后期添加富文本组件 -->
          <quill-editor v-model="formData.answer" />
        </el-form-item>
        <el-form-item
          label="题目备注："
          prop="remarks"
        >
          <el-input
            type="textarea"
            :rows="4"
            style="width:400px"
            v-model="formData.remarks"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="试题标签"
          prop="tags"
        >
          <el-select
            placeholder="请选择试题标签"
            v-model="formData.tags"
            @focus="getTagsData"
            multiple
          >
            <el-option
              v-for="item in tags"
              :key="item.tagName"
              :label="item.tagName"
              :value="item.tagName"
            ></el-option>

          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="success"
            @click="btnOk"
            v-if="this.formData.id"
          >确认修改</el-button>
          <el-button
            v-else
            type="primary"
            @click="btnOk"
          >确认提交</el-button>
        </el-form-item>
      </el-form>

    </el-card>

  </div>
</template>

<script>
import { list as tagsList } from '@/api/hmmm/tags'
import { direction, questionType, difficulty } from '@/api/hmmm/constants'
import { provinces, citys } from '@/api/hmmm/citys'
import { add, detail, update } from '@/api/hmmm/questions'
import { simple } from '@/api/hmmm/subjects'
import { list } from '@/api/hmmm/directorys'
import { list as enterpriseList } from '@/api/hmmm/companys'
const letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
export default {
  data () {
    return {
      i: 0,
      // 表单数据存储
      formData: {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 城市
        city: '', // 地区
        direction: '', // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: '', // 题干
        options: this.Options, // 选项
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: [] // 试题标签
      },
      subject: [], // 获取到的subject学科下拉框数据
      catalog: [], // 获取到的catalog目录下拉框数据
      enterprise: [], // 获取到的enterprise企业下拉框数据
      provinces: provinces(), // 城市数据
      citys: '', // 地区数据
      direction: direction, // 方向
      questionType: questionType, // 题型选择按钮数据
      difficulty: difficulty, // 难度按钮数据
      tags: [], // 获取到的tags试题标签下拉框数据
      options: [], // 存储选项数据
      isRadio: '', // 选项单选选中
      isCheckbox: [], // 选项多选选中
      // 表单验证规则
      formDataRules: {
        subjectID: [{
          required: true, message: '请选择学科', trigger: 'change'
        }],
        catalogID: [{
          required: true, message: '请选择目录', trigger: 'change'
        }],
        enterpriseID: [{
          required: true, message: '请选择企业', trigger: 'change'
        }],
        province: [{
          required: true, message: '请选择地区', trigger: 'change'
        }],
        city: [{
          required: true, message: '请选择地区', trigger: 'change'
        }],
        direction: [{
          required: true, message: '请选择方向', trigger: 'change'
        }],
        questionType: [{
          required: true, message: '请选择题型', trigger: 'change'
        }],
        difficulty: [{
          required: true, message: '请选择难度', trigger: 'change'
        }],
        question: [{
          required: true, message: '请输入题干', trigger: 'blur'
        }],
        answer: [{
          required: true, message: '请输入答案解析', trigger: 'blur'
        }],
        tags: [{
          required: true, message: '请选择试题标签', trigger: 'change'
        }]
      }
    }
  },
  computed: {
    title () {
      return this.formData.id ? '试题修改' : '试题录入'
    }
  },
  created () {
    this.isEdit()
    this.getparams()
    this.Options()
  },
  methods: {
    // 循环初始化选项数据
    Options () {
      const options = []
      for (var i = 0; i < 4; i++) {
        options.push({
          code: letters[i],
          title: '',
          isRight: 0
        })
      }
      this.options = options
    },
    // 判断是跳转过来的还是点击进来的
    async isEdit () {
      if (this.$route.query.id) {
        // 有值说明是跳转过来的 要通过传的id获取数据回写表单
        const { data } = await detail({ id: this.$route.query.id })
        this.formData = data
        // 处理数据选中问题
        if (this.formData.questionType === '1') {
          this.isRadio = data.options.filter(item => {
            if (item.isRight === 1) return item.code
          })[0].code
        } else if (this.formData.questionType === '2') {
          this.isCheckbox = data.options.filter(item => {
            if (item.isRight === 1) {
              return item
            }
          }).map(item => item.code)
        }
        this.options = data.options
        // 因为后端要的是字符串  然而前端要的是数组 获取到数据后 把字符串数据切割为数组
        this.formData.tags = data.tags.split(',')
      }
    },
    // 获取需要的下拉框数据
    getparams () {
      this.getSubjectData()
      this.getCatalogData()
      this.getEnterpriseData()
      this.getTagsData()
    },
    // 获取学科数据
    async getSubjectData () {
      const { data } = await simple()
      this.subject = data
    },
    // 获取目录数据
    async getCatalogData () {
      // 获取到总的条数
      const { data } = await list()
      // 条件设置为总条数 确保获取到全部数据
      const result = await list({
        page: 1, pagesize: data.counts
      })
      this.catalog = result.data.items
    },
    // 获取企业数据
    async getEnterpriseData () {
      // 获取到总的条数
      const { data } = await enterpriseList()
      // 条件设置为总条数 确保获取到全部数据
      const result = await enterpriseList({
        page: 1, pagesize: data.counts
      })
      this.enterprise = result.data.items
    },
    // 获取试题标签数据
    async getTagsData () {
      // 获取到总的条数
      const { data } = await tagsList()
      // 条件设置为总条数 确保获取到全部数据
      const result = await tagsList({
        page: 1, pagesize: data.counts
      })
      this.tags = result.data.items
    },
    // 当选择区选择框获取焦点触发事件获取数据 根据市获得区的数据
    getCitysData () {
      // this.formData.province 选择的是市
      // 根据市获取区的数据并赋值
      this.citys = citys(this.formData.province)
    },
    // 点击按钮 添加选项
    btnAdd () {
      this.options.push({
        code: letters[this.options.length],
        title: '',
        isRight: 0
      })
    },
    // 提交添加按钮
    async btnOk () {
      // 验证表单
      await this.$refs.addFormData.validate()
      // 通过后按照后端要求格式化数据
      this.formData.tags = this.formData.tags.join(',')
      if (this.formData.questionType === '1') {
        this.options = this.options.map(item => {
          if (item.code === this.isRadio) {
            item.isRight = 1
          }
          return item
        })
      } else if (this.formData.questionType === '2') {
        this.options.map(item => {
          if (item.code === this.isCheckbox[this.i]) {
            this.i += 1
            item.isRight = 1
          }
          return item
        })
      }
      this.formData.options = this.options
      try {
        if (this.formData.id) {
          // 如果有id 表示是修改
          await update(this.formData)
        } else {
          // 添加
          await add(this.formData)
        }
      } catch (err) {
        console.log(err)
      }
      this.$message.success(`${this.title}成功`)
      // 重置表单
      this.formData = {
        subjectID: '' + '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 城市
        city: '', // 地区
        direction: '', // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: '', // 题干
        options: [], // 选项
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: [] // 试题标签
      }
      // 充值验证规则
      this.$refs.addFormData.resetFields()
      // 重置 i 项
      this.i = 0
      // 跳转页面
      this.$router.push('/questions/list')
    }
  }
}
</script>

<style lang='sass'>
.el-select
  width: 400px
.avatar-uploader
  display: inline-block
.avatar-uploader .el-upload:hover
  border-color: #409EFF
.avatar-uploader .el-upload--picture-card
  width: 100px
  height: 60px
  line-height: 60px
  vertical-align: middle
  margin-left: 4px
  background-color: #fff
.option_item
  padding-bottom: 20px
.el-upload
  position: relative
.el-upload .el-icon-circle-close
  font-size: 18px
  position: absolute
  color: #999
  right: -9px
  top: -9px
.quill-editor
  height: 220px
  margin-bottom: 90px
</style>
